#include "checkboxdelegate.h"
#include <QApplication>
#include <QCheckBox>
CheckBoxDelegate::CheckBoxDelegate(QObject *parent)
    : QStyledItemDelegate{parent}
{}

void CheckBoxDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    if (index.column() == 0) {
        QStyleOptionButton checkBoxOption;
        //qDebug() << index.data(Qt::CheckStateRole).toBool();
        QRect rect(option.rect.left() + 5, option.rect.top(), option.rect.right(), option.rect.bottom());
        checkBoxOption.state = index.data(Qt::CheckStateRole).toBool() ? QStyle::State_On : QStyle::State_Off;
        checkBoxOption.rect = rect;
        QApplication::style()->drawControl(QStyle::CE_CheckBox, &checkBoxOption, painter);
    } else {
        QStyledItemDelegate::paint(painter, option, index);
    }
}

QWidget *CheckBoxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QCheckBox *editor = new QCheckBox(parent);
    return editor;
}

void CheckBoxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    bool checked = index.model()->data(index, Qt::CheckStateRole).toBool();
    QCheckBox *checkBox = qobject_cast<QCheckBox *>(editor);
    if (checkBox) {
        checkBox->setChecked(checked);
    }
}

void CheckBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
                  const QModelIndex &index) const
{
    QCheckBox *checkBox = qobject_cast<QCheckBox *>(editor);
    if (checkBox) {
        model->setData(index, checkBox->isChecked(), Qt::CheckStateRole);
    }
}
